package csel.model;

import java.io.*;

class SerializationLoaderSaver implements LoaderSaver
{
	public GameData load(String filepath) throws FileNotFoundException
	{
		FileInputStream fileIn;
		ObjectInputStream serializer;
		GameData data;

		fileIn = new FileInputStream(filepath);

		try
		{
			serializer = new ObjectInputStream(fileIn);
			data = (GameData)serializer.readObject();
			
			/*
			 * GC would call these, but I'll call now to avoid locking the file any
			 * longer than necessary.
			 */
			fileIn.close();
			serializer.close();
		}
		catch (IOException ex)
		{
			throw new GameLoadException("Could not read specified saved gamed file.", ex);
		}
		catch (ClassNotFoundException ex)
		{
			throw new GameLoadException("Corrupt saved game.", ex);
		}

		return data;
	}

	public void save(String filepath, GameData data)
			throws FileNotFoundException, IOException
	{
		FileOutputStream fileOut = new FileOutputStream(filepath);
		ObjectOutputStream serializer = new ObjectOutputStream(fileOut);

		serializer.writeObject(data);

		/*
		 * GC would call these, but I'll call now to avoid locking the file any
		 * longer than necessary.
		 */
		serializer.close();
		fileOut.close();
	}

}
